package vn.edu.ptithcm.pim.service;

import java.util.List;

import javax.activation.DataSource;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;

import org.apache.log4j.Logger;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;

import vn.edu.ptithcm.pim.common.bean.Attachment;
import vn.edu.ptithcm.pim.common.bean.SendMailObject;

public class SendMailService {
	private JavaMailSender mailSender;
	private VelocityEngine velocityEngine;

	Logger log = Logger.getLogger(SendMailService.class);

	public void send(final SendMailObject sendMailObject) throws MailException {
		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
				MimeMessageHelper message = new MimeMessageHelper(mimeMessage,
						true, "UTF-8");
				message.setSubject(sendMailObject.getSuject());
				message.setFrom(sendMailObject.getFrom());
				message.setTo(sendMailObject.getTo());

				if (sendMailObject.getBcc() != null
						&& sendMailObject.getBcc().size() > 0) {
					message.setBcc(sendMailObject.getBcc().toArray(
							new String[0]));
				}

				String text = VelocityEngineUtils.mergeTemplateIntoString(
						velocityEngine, sendMailObject.getTemplate(), "utf-8",
						sendMailObject.getData());
				message.setText(text, true);

				List<Attachment> attachments = sendMailObject
						.getAttachedFiles();

				if (attachments != null && attachments.size() > 0) {
					for (Attachment attachment : attachments) {
						String filename = attachment.getFilename();
						DataSource dataSource = new ByteArrayDataSource(
								attachment.getData(), attachment.getMimeType());
						if (attachment.isInline()) {
							message.addInline(filename, dataSource);
						} else {
							message.addAttachment(filename, dataSource);
						}
					}
				}
			}
		};
		mailSender.send(preparator);
	}

	public JavaMailSender getMailSender() {
		return mailSender;
	}

	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	public VelocityEngine getVelocityEngine() {
		return velocityEngine;
	}

	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}

}
